// pages/index/recommend/recommend.js
import PubSub, { publish } from 'pubsub-js'
import request from "../../../utils/request";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    day: "",
    month: "",
    recommendSongs: [],
    index:0
  },

  /**
   * 生命周期函数--监听页面加载
   */

  onLoad: function (options) {
    this.setData({
      day: new Date().getDate(),
      month: new Date().getMonth() + 1,
    });

    this.getDailyRecommend();
    // 订阅 detail发布的消息
    this.appInstance = getApp()
    const currentSongId = this.appInstance.appData.currentSongId
    PubSub.subscribe('getChange',(msg,change) => {
      const {recommendSongs,index} = this.data
      let indexCopy = index
      if(change === 'pre'){
        // 当前没有歌曲正在播放
        if(index === 0){
          indexCopy = recommendSongs.length -1
        } else {
          indexCopy -=1
        }
      }else{
        if(index  === recommendSongs.length -1) {
          indexCopy = 0 
        } else {
          indexCopy +=1
        }
      }
      this.setData({
        index:indexCopy
      })
      PubSub.publish('changeSong', recommendSongs[indexCopy])
    })
  },
  async getDailyRecommend() {
    const recommendData = await request("/recommend/songs");
    if (recommendData.code === 200) {
      this.setData({
        recommendSongs: recommendData.recommend,
      });
    }
  },
  toDetail(e) {
    // 需要拿到循环遍历的元素 可以给遍历的当前元素 绑定 data-x  然后在e.currentTarget.dataset中获取
    let {song,index} = e.currentTarget.dataset;
    this.setData({
      index
    }) 
    wx.navigateTo({
      url: "/pages/songDetail/songDetial",
      success: (res) => {
        res.eventChannel.emit("getSongDetail", { data: song });
      },
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
});
